<!--<!DOCTYPE html>-->
<!--<html lang="zh-CN">-->
<!--<head>-->
<!--    <meta charset="UTF-8">-->
<!--    <meta name="viewport" content="width=device-width, initial-scale=1.0">-->
<!--    <title>药品管理系统 - 销售管理</title>-->
<!--    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">-->
<!--    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>-->
<!--    <script src="https://unpkg.com/element-ui/lib/index.js"></script>-->
<!--    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>-->
<!--    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>-->
<!--    <style>-->
<!--        * {-->
<!--            margin: 0;-->
<!--            padding: 0;-->
<!--            box-sizing: border-box;-->
<!--        }-->
<!--        body {-->
<!--            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;-->
<!--            background-color: #f5f7fa;-->
<!--            color: #606266;-->
<!--        }-->
<!--        .app-container {-->
<!--            min-height: 100vh;-->
<!--            display: flex;-->
<!--            flex-direction: column;-->
<!--        }-->
<!--        .header {-->
<!--            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);-->
<!--            color: white;-->
<!--            padding: 15px 20px;-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            justify-content: space-between;-->
<!--        }-->
<!--        .logo-area {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--        }-->
<!--        .logo {-->
<!--            width: 50px;-->
<!--            height: 50px;-->
<!--            margin-right: 15px;-->
<!--            background: rgba(255, 255, 255, 0.2);-->
<!--            border-radius: 50%;-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            justify-content: center;-->
<!--            font-size: 24px;-->
<!--            font-weight: bold;-->
<!--        }-->
<!--        .system-name {-->
<!--            font-size: 22px;-->
<!--            font-weight: bold;-->
<!--        }-->
<!--        .nav-menu {-->
<!--            display: flex;-->
<!--            background-color: #304156;-->
<!--            padding: 0 20px;-->
<!--        }-->
<!--        .nav-item {-->
<!--            padding: 15px 20px;-->
<!--            color: #bfcbd9;-->
<!--            cursor: pointer;-->
<!--            transition: all 0.3s;-->
<!--        }-->
<!--        .nav-item:hover, .nav-item.active {-->
<!--            color: #409EFF;-->
<!--            background-color: #263445;-->
<!--            border-bottom: 2px solid #409EFF;-->
<!--        }-->
<!--        .main-content {-->
<!--            flex: 1;-->
<!--            padding: 20px;-->
<!--        }-->
<!--        .card-container {-->
<!--            background: white;-->
<!--            border-radius: 4px;-->
<!--            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);-->
<!--            padding: 20px;-->
<!--            margin-bottom: 20px;-->
<!--        }-->
<!--        .search-bar {-->
<!--            margin-bottom: 20px;-->
<!--            padding: 20px;-->
<!--            background: white;-->
<!--            border-radius: 4px;-->
<!--            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);-->
<!--        }-->
<!--        .pagination-container {-->
<!--            margin-top: 20px;-->
<!--            text-align: right;-->
<!--        }-->
<!--        .stats-container {-->
<!--            display: grid;-->
<!--            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));-->
<!--            gap: 20px;-->
<!--            margin-bottom: 20px;-->
<!--        }-->
<!--        .stat-card {-->
<!--            background: white;-->
<!--            border-radius: 4px;-->
<!--            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);-->
<!--            padding: 20px;-->
<!--            text-align: center;-->
<!--        }-->
<!--        .stat-value {-->
<!--            font-size: 24px;-->
<!--            font-weight: bold;-->
<!--            color: #409EFF;-->
<!--            margin: 10px 0;-->
<!--        }-->
<!--        .stat-label {-->
<!--            color: #909399;-->
<!--            font-size: 14px;-->
<!--        }-->
<!--        .chart-container {-->
<!--            height: 300px;-->
<!--            margin-top: 20px;-->
<!--        }-->
<!--        .footer {-->
<!--            text-align: center;-->
<!--            padding: 15px 0;-->
<!--            color: #909399;-->
<!--            font-size: 14px;-->
<!--            background-color: #f5f7fa;-->
<!--            border-top: 1px solid #e6e6e6;-->
<!--        }-->
<!--        .positive-amount {-->
<!--            color: #67C23A;-->
<!--        }-->
<!--        .action-buttons {-->
<!--            margin-bottom: 15px;-->
<!--        }-->
<!--        .readonly-input .el-input__inner {-->
<!--            background-color: #f5f7fa;-->
<!--            color: #606266;-->
<!--            cursor: not-allowed;-->
<!--        }-->
<!--    </style>-->
<!--</head>-->
<!--<body>-->
<!--<div id="app" class="app-container">-->
<!--    <header class="header">-->
<!--        <div class="logo-area">-->
<!--            <div class="logo">药</div>-->
<!--            <div class="system-name">药品管理系统</div>-->
<!--        </div>-->
<!--        <div>-->
<!--            <el-dropdown @command="handleUserCommand">-->
<!--                <span class="el-dropdown-link" style="color: white; cursor: pointer;">-->
<!--                    {{ currentUser.username }} ({{ formatRole(currentUser.role) }})<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--                </span>-->
<!--                <el-dropdown-menu slot="dropdown">-->
<!--                    <el-dropdown-item command="profile">个人信息</el-dropdown-item>-->
<!--                    <el-dropdown-item command="logout">退出登录</el-dropdown-item>-->
<!--                </el-dropdown-menu>-->
<!--            </el-dropdown>-->
<!--        </div>-->
<!--    </header>-->

<!--    <nav class="nav-menu">-->
<!--        <div class="nav-item" @click="navigateTo('index.html')">首页</div>-->
<!--        <div class="nav-item" @click="navigateTo('medicine.html')">药品管理</div>-->
<!--        <div class="nav-item" @click="navigateTo('inventory.html')">库存管理</div>-->
<!--        <div class="nav-item active">销售管理</div>-->
<!--        <div class="nav-item" @click="navigateTo('user.html')" v-if="currentUser.role === 'admin'">用户管理</div>-->
<!--        <div class="nav-item" @click="navigateTo('log.html')" v-if="currentUser.role === 'admin'">操作日志</div>-->
<!--    </nav>-->

<!--    <main class="main-content">-->
<!--        <h2 style="margin-bottom: 20px;">销售管理</h2>-->

<!--        <div class="stats-container">-->
<!--            <div class="stat-card">-->
<!--                <div class="stat-label">今日销售额</div>-->
<!--                <div class="stat-value">¥{{ salesStats.todaySales || 0 }}</div>-->
<!--            </div>-->
<!--            <div class="stat-card">-->
<!--                <div class="stat-label">本月销售额</div>-->
<!--                <div class="stat-value">¥{{ salesStats.monthSales || 0 }}</div>-->
<!--            </div>-->
<!--            <div class="stat-card">-->
<!--                <div class="stat-label">今日销售单数</div>-->
<!--                <div class="stat-value">{{ salesStats.todayOrders || 0 }}</div>-->
<!--            </div>-->
<!--            <div class="stat-card">-->
<!--                <div class="stat-label">热销药品</div>-->
<!--                <div class="stat-value">{{ salesStats.topMedicine || '无' }}</div>-->
<!--            </div>-->
<!--        </div>-->

<!--        <div class="search-bar">-->
<!--            <el-form :inline="true" :model="searchForm">-->
<!--                <el-form-item label="药品名称">-->
<!--                    <el-input v-model="searchForm.medicineName" placeholder="请输入药品名称" clearable></el-input>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="销售日期">-->
<!--                    <el-date-picker-->
<!--                            v-model="searchForm.dateRange"-->
<!--                            type="daterange"-->
<!--                            range-separator="至"-->
<!--                            start-placeholder="开始日期"-->
<!--                            end-placeholder="结束日期"-->
<!--                            value-format="yyyy-MM-dd">-->
<!--                    </el-date-picker>-->
<!--                </el-form-item>-->
<!--                <el-form-item>-->
<!--                    <el-button type="primary" @click="loadSales">查询</el-button>-->
<!--                    <el-button @click="resetSearch">重置</el-button>-->
<!--                    <el-button type="success" @click="handleAddSale" v-if="currentUser.role === 'sales' || currentUser.role === 'admin'">新增销售</el-button>-->
<!--                </el-form-item>-->
<!--            </el-form>-->
<!--        </div>-->

<!--        <div class="card-container">-->
<!--            <div class="action-buttons">-->
<!--                <el-button type="primary" size="small" @click="exportSales">导出数据</el-button>-->
<!--            </div>-->

<!--            <el-table :data="salesList" border stripe v-loading="loading">-->
<!--                <el-table-column prop="id" label="销售ID" width="100"></el-table-column>-->
<!--                <el-table-column label="药品名称" min-width="150">-->
<!--                    <template slot-scope="scope">-->
<!--                        {{ scope.row.medicine ? scope.row.medicine.name : '未知药品' }}-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column prop="quantity" label="数量" width="80"></el-table-column>-->
<!--                <el-table-column label="单价" width="100">-->
<!--                    <template slot-scope="scope">-->
<!--                        ¥{{ scope.row.salePrice || '未知' }}-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column prop="totalAmount" label="总金额" width="120">-->
<!--                    <template slot-scope="scope">-->
<!--                        <span class="positive-amount">¥{{ scope.row.totalAmount }}</span>-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column prop="saleTime" label="销售时间" width="160">-->
<!--                    <template slot-scope="scope">-->
<!--                        {{ formatDateTime(scope.row.saleTime) }}-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column label="操作员" width="100">-->
<!--                    <template slot-scope="scope">-->
<!--                        {{ scope.row.operator ? scope.row.operator.username : '未知' }}-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column label="操作" width="120" fixed="right" v-if="currentUser.role === 'admin'">-->
<!--                    <template slot-scope="scope">-->
<!--                        <el-button size="mini" type="danger" @click="handleDeleteSale(scope.row)">删除</el-button>-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--            </el-table>-->

<!--            <div class="pagination-container">-->
<!--                <el-pagination-->
<!--                        @size-change="handleSizeChange"-->
<!--                        @current-change="handleCurrentChange"-->
<!--                        :current-page="pagination.currentPage"-->
<!--                        :page-sizes="[10, 20, 50, 100]"-->
<!--                        :page-size="pagination.pageSize"-->
<!--                        layout="total, sizes, prev, pager, next, jumper"-->
<!--                        :total="pagination.total">-->
<!--                </el-pagination>-->
<!--            </div>-->
<!--        </div>-->

<!--        <div class="card-container">-->
<!--            <h3>销售趋势图</h3>-->
<!--            <div class="chart-container" id="salesChart"></div>-->
<!--        </div>-->

<!--        &lt;!&ndash; 添加销售记录对话框 &ndash;&gt;-->
<!--        <el-dialog-->
<!--                :title="dialogTitle"-->
<!--                :visible.sync="dialogVisible"-->
<!--                width="600px"-->
<!--                :close-on-click-modal="false">-->
<!--            <el-form :model="saleForm" :rules="rules" ref="saleForm" label-width="100px">-->
<!--                <el-form-item label="药品" prop="medicineId">-->
<!--                    <el-select-->
<!--                            v-model="saleForm.medicineId"-->
<!--                            placeholder="请选择药品"-->
<!--                            filterable-->
<!--                            @change="onMedicineChange"-->
<!--                            style="width: 100%;">-->
<!--                        <el-option-->
<!--                                v-for="item in availableMedicines"-->
<!--                                :key="item.id"-->
<!--                                :label="item.name"-->
<!--                                :value="item.id">-->
<!--                            <span style="float: left">{{ item.name }}</span>-->
<!--                            <span style="float: right; color: #8492a6; font-size: 13px">库存: {{ item.currentStock }}</span>-->
<!--                        </el-option>-->
<!--                    </el-select>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="单价">-->
<!--                    <el-input-->
<!--                            v-model="saleForm.salePrice"-->
<!--                            :readonly="true"-->
<!--                            class="readonly-input"-->
<!--                            style="width: 100%;">-->
<!--                        <template slot="prepend">¥</template>-->
<!--                    </el-input>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="数量" prop="quantity">-->
<!--                    <el-input-number-->
<!--                            v-model="saleForm.quantity"-->
<!--                            :min="1"-->
<!--                            :max="maxQuantity"-->
<!--                            @change="calculateTotal"-->
<!--                            style="width: 100%;"></el-input-number>-->
<!--                    <div style="color: #909399; font-size: 12px; margin-top: 5px;">-->
<!--                        可用库存: {{ currentStock }}-->
<!--                    </div>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="总金额">-->
<!--                    <el-input v-model="saleForm.totalAmount" readonly style="width: 100%;">-->
<!--                        <template slot="prepend">¥</template>-->
<!--                    </el-input>-->
<!--                </el-form-item>-->
<!--            </el-form>-->
<!--            <span slot="footer" class="dialog-footer">-->
<!--                <el-button @click="dialogVisible = false">取 消</el-button>-->
<!--                <el-button type="primary" @click="submitSaleForm">确 定</el-button>-->
<!--            </span>-->
<!--        </el-dialog>-->
<!--    </main>-->

<!--    <footer class="footer">© 2023 药品管理系统 - 版权所有</footer>-->
<!--</div>-->

<!--<script>-->
<!--    new Vue({-->
<!--        el: '#app',-->
<!--        data() {-->
<!--            return {-->
<!--                activeNav: 'sale',-->
<!--                currentUser: { id: null, username: '', role: '' },-->
<!--                searchForm: {-->
<!--                    medicineName: '',-->
<!--                    dateRange: []-->
<!--                },-->
<!--                salesList: [],-->
<!--                salesStats: {},-->
<!--                medicines: [],-->
<!--                availableMedicines: [], // 有库存的药品-->
<!--                loading: false,-->
<!--                pagination: {-->
<!--                    currentPage: 1,-->
<!--                    pageSize: 10,-->
<!--                    total: 0-->
<!--                },-->
<!--                dialogVisible: false,-->
<!--                dialogTitle: '新增销售记录',-->
<!--                saleForm: {-->
<!--                    medicineId: '',-->
<!--                    salePrice: 0,-->
<!--                    quantity: 1,-->
<!--                    totalAmount: 0-->
<!--                },-->
<!--                currentStock: 0,-->
<!--                maxQuantity: 1,-->
<!--                rules: {-->
<!--                    medicineId: [{ required: true, message: '请选择药品', trigger: 'change' }],-->
<!--                    quantity: [-->
<!--                        { required: true, message: '请输入销售数量', trigger: 'blur' },-->
<!--                        { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }-->
<!--                    ]-->
<!--                },-->
<!--                salesChart: null-->
<!--            };-->
<!--        },-->
<!--        mounted() {-->
<!--            this.loadCurrentUser();-->
<!--            this.loadSales();-->
<!--            this.loadSalesStats();-->
<!--            this.loadMedicines();-->
<!--            this.initChart();-->

<!--            // 窗口大小变化时重绘图表-->
<!--            window.addEventListener('resize', () => {-->
<!--                if (this.salesChart) {-->
<!--                    this.salesChart.resize();-->
<!--                }-->
<!--            });-->
<!--        },-->
<!--        methods: {-->
<!--            loadCurrentUser() {-->
<!--                // 尝试从本地存储获取用户信息-->
<!--                const savedUser = localStorage.getItem('currentUser');-->
<!--                if (savedUser) {-->
<!--                    this.currentUser = JSON.parse(savedUser);-->
<!--                    return;-->
<!--                }-->

<!--                // 如果本地存储没有，尝试从session获取-->
<!--                axios.get('/pms/user/current').then(response => {-->
<!--                    if (response.data.success) {-->
<!--                        this.currentUser = response.data.data;-->
<!--                        localStorage.setItem('currentUser', JSON.stringify(response.data.data));-->
<!--                    } else {-->
<!--                        this.$message.error('获取用户信息失败');-->
<!--                        window.location.href = 'login.html';-->
<!--                    }-->
<!--                }).catch(error => {-->
<!--                    console.error('获取用户信息失败:', error);-->
<!--                    window.location.href = 'login.html';-->
<!--                });-->
<!--            },-->

<!--            loadSales() {-->
<!--                this.loading = true;-->
<!--                const params = {-->
<!--                    page: this.pagination.currentPage - 1, // 后端通常从0开始-->
<!--                    size: this.pagination.pageSize,-->
<!--                    medicineName: this.searchForm.medicineName-->
<!--                };-->

<!--                // 添加日期范围参数-->
<!--                if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {-->
<!--                    params.startDate = this.searchForm.dateRange[0];-->
<!--                    params.endDate = this.searchForm.dateRange[1];-->
<!--                }-->

<!--                axios.get('/pms/sale/list', {-->
<!--                    params,-->
<!--                    headers: {-->
<!--                        'Content-Type': 'application/json'-->
<!--                    }-->
<!--                }).then(response => {-->
<!--                    if (response.data.success) {-->
<!--                        this.salesList = response.data.data.content || response.data.data;-->
<!--                        // 如果后端返回分页信息，这里需要调整-->
<!--                        if (response.data.data.totalElements) {-->
<!--                            this.pagination.total = response.data.data.totalElements;-->
<!--                        } else {-->
<!--                            this.pagination.total = this.salesList.length;-->
<!--                        }-->
<!--                    } else {-->
<!--                        if (response.status === 401) {-->
<!--                            this.$message.error('用户未登录或会话已过期');-->
<!--                            this.handleLogout();-->
<!--                        } else {-->
<!--                            this.$message.error(response.data.message || '获取销售记录失败');-->
<!--                        }-->
<!--                    }-->
<!--                    this.loading = false;-->
<!--                }).catch(error => {-->
<!--                    console.error('获取销售记录失败:', error);-->
<!--                    if (error.response && error.response.status === 401) {-->
<!--                        this.$message.error('用户未登录或会话已过期');-->
<!--                        this.handleLogout();-->
<!--                    } else {-->
<!--                        this.$message.error('获取销售记录失败');-->
<!--                    }-->
<!--                    this.loading = false;-->
<!--                });-->
<!--            },-->

<!--            loadSalesStats() {-->
<!--                // 计算今天和本月的开始结束日期-->
<!--                const today = new Date();-->
<!--                const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);-->

<!--                const formatDate = (date) => {-->
<!--                    return date.toISOString().split('T')[0];-->
<!--                };-->

<!--                const params = {-->
<!--                    startDate: formatDate(firstDayOfMonth),-->
<!--                    endDate: formatDate(today)-->
<!--                };-->

<!--                axios.get('/pms/sale/statistics', { params }).then(response => {-->
<!--                    if (response.data.success) {-->
<!--                        this.salesStats = {-->
<!--                            monthSales: response.data.totalSales || 0,-->
<!--                            todaySales: response.data.totalSales || 0, // 简化处理，实际应根据当天数据计算-->
<!--                            todayOrders: response.data.recordCount || 0,-->
<!--                            topMedicine: '待实现' // 需要后端支持-->
<!--                        };-->
<!--                    }-->
<!--                }).catch(error => {-->
<!--                    console.error('获取销售统计失败:', error);-->
<!--                });-->
<!--            },-->

<!--            loadMedicines() {-->
<!--                axios.get('/pms/medicine/list').then(response => {-->
<!--                    if (response.data.success) {-->
<!--                        this.medicines = response.data.data.content || response.data.data;-->

<!--                        // 过滤有库存的药品-->
<!--                        this.availableMedicines = this.medicines.filter(medicine =>-->
<!--                            medicine.currentStock > 0 && medicine.status === 1-->
<!--                        );-->
<!--                    }-->
<!--                }).catch(error => {-->
<!--                    console.error('获取药品列表失败:', error);-->
<!--                });-->
<!--            },-->

<!--            resetSearch() {-->
<!--                this.searchForm = {-->
<!--                    medicineName: '',-->
<!--                    dateRange: []-->
<!--                };-->
<!--                this.pagination.currentPage = 1;-->
<!--                this.loadSales();-->
<!--            },-->

<!--            handleSizeChange(size) {-->
<!--                this.pagination.pageSize = size;-->
<!--                this.pagination.currentPage = 1; // 重置到第一页-->
<!--                this.loadSales();-->
<!--            },-->

<!--            handleCurrentChange(page) {-->
<!--                this.pagination.currentPage = page;-->
<!--                this.loadSales();-->
<!--            },-->

<!--            handleAddSale() {-->
<!--                // 检查权限-->
<!--                if (this.currentUser.role !== 'sales' && this.currentUser.role !== 'admin') {-->
<!--                    this.$message.error('您没有销售权限');-->
<!--                    return;-->
<!--                }-->

<!--                this.dialogTitle = '新增销售记录';-->
<!--                this.saleForm = {-->
<!--                    medicineId: '',-->
<!--                    salePrice: 0,-->
<!--                    quantity: 1,-->
<!--                    totalAmount: 0-->
<!--                };-->
<!--                this.currentStock = 0;-->
<!--                this.maxQuantity = 1;-->
<!--                this.dialogVisible = true;-->

<!--                if (this.$refs.saleForm) {-->
<!--                    this.$refs.saleForm.clearValidate();-->
<!--                }-->
<!--            },-->

<!--            onMedicineChange(medicineId) {-->
<!--                const medicine = this.medicines.find(m => m.id === medicineId);-->
<!--                if (medicine) {-->
<!--                    this.saleForm.salePrice = medicine.price;-->
<!--                    this.currentStock = medicine.currentStock;-->
<!--                    this.maxQuantity = medicine.currentStock;-->
<!--                    this.calculateTotal();-->
<!--                }-->
<!--            },-->

<!--            calculateTotal() {-->
<!--                this.saleForm.totalAmount = (this.saleForm.quantity * this.saleForm.salePrice).toFixed(2);-->
<!--            },-->

<!--            submitSaleForm() {-->
<!--                this.$refs.saleForm.validate(valid => {-->
<!--                    if (valid) {-->
<!--                        axios.post('/pms/sale/add', this.saleForm).then(response => {-->
<!--                            if (response.data.success) {-->
<!--                                this.$message.success('销售记录添加成功');-->
<!--                                this.dialogVisible = false;-->
<!--                                this.loadSales();-->
<!--                                this.loadSalesStats();-->
<!--                                this.loadMedicines(); // 重新加载药品列表以更新库存-->
<!--                                this.loadChartData();-->
<!--                            } else {-->
<!--                                this.$message.error(response.data.message || '添加销售记录失败');-->
<!--                            }-->
<!--                        }).catch(error => {-->
<!--                            console.error('添加销售记录失败:', error);-->
<!--                            if (error.response && error.response.status === 403) {-->
<!--                                this.$message.error('权限不足，无法添加销售记录');-->
<!--                            } else if (error.response && error.response.status === 400) {-->
<!--                                this.$message.error('库存不足或数据验证失败');-->
<!--                            } else {-->
<!--                                this.$message.error('添加销售记录失败');-->
<!--                            }-->
<!--                        });-->
<!--                    } else {-->
<!--                        return false;-->
<!--                    }-->
<!--                });-->
<!--            },-->

<!--            handleDeleteSale(row) {-->
<!--                this.$confirm('确定要删除该销售记录吗?', '提示', {-->
<!--                    confirmButtonText: '确定',-->
<!--                    cancelButtonText: '取消',-->
<!--                    type: 'warning'-->
<!--                }).then(() => {-->
<!--                    axios.delete(`/pms/sale/delete/${row.id}`).then(response => {-->
<!--                        if (response.data.success) {-->
<!--                            this.$message.success('删除成功');-->
<!--                            this.loadSales();-->
<!--                            this.loadSalesStats();-->
<!--                            this.loadMedicines(); // 重新加载药品列表以更新库存-->
<!--                            this.loadChartData();-->
<!--                        } else {-->
<!--                            this.$message.error(response.data.message || '删除失败');-->
<!--                        }-->
<!--                    }).catch(error => {-->
<!--                        console.error('删除销售记录失败:', error);-->
<!--                        this.$message.error('删除销售记录失败');-->
<!--                    });-->
<!--                }).catch(() => {});-->
<!--            },-->

<!--            exportSales() {-->
<!--                const params = {-->
<!--                    medicineName: this.searchForm.medicineName-->
<!--                };-->

<!--                if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {-->
<!--                    params.startDate = this.searchForm.dateRange[0];-->
<!--                    params.endDate = this.searchForm.dateRange[1];-->
<!--                }-->

<!--                axios.get('/pms/sale/export', {-->
<!--                    params,-->
<!--                    responseType: 'blob'-->
<!--                }).then(response => {-->
<!--                    const url = window.URL.createObjectURL(new Blob([response.data]));-->
<!--                    const link = document.createElement('a');-->
<!--                    link.href = url;-->
<!--                    link.setAttribute('download', '销售记录.xlsx');-->
<!--                    document.body.appendChild(link);-->
<!--                    link.click();-->
<!--                    document.body.removeChild(link);-->
<!--                }).catch(error => {-->
<!--                    console.error('导出销售记录失败:', error);-->
<!--                    this.$message.error('导出销售记录失败');-->
<!--                });-->
<!--            },-->

<!--            initChart() {-->
<!--                this.salesChart = echarts.init(document.getElementById('salesChart'));-->
<!--                this.loadChartData();-->
<!--            },-->

<!--            loadChartData() {-->
<!--                // 获取最近30天的销售数据-->
<!--                const endDate = new Date();-->
<!--                const startDate = new Date();-->
<!--                startDate.setDate(startDate.getDate() - 30);-->

<!--                axios.get('/pms/sale/records/date-range', {-->
<!--                    params: {-->
<!--                        startDate: startDate.toISOString().split('T')[0],-->
<!--                        endDate: endDate.toISOString().split('T')[0]-->
<!--                    }-->
<!--                }).then(response => {-->
<!--                    if (response.data.success) {-->
<!--                        this.processChartData(response.data.data);-->
<!--                    }-->
<!--                }).catch(error => {-->
<!--                    console.error('获取图表数据失败:', error);-->
<!--                    // 使用模拟数据作为备选-->
<!--                    this.useMockChartData();-->
<!--                });-->
<!--            },-->

<!--            processChartData(salesData) {-->
<!--                // 按日期分组汇总销售数据-->
<!--                const dateMap = {};-->

<!--                salesData.forEach(record => {-->
<!--                    const date = record.saleTime.split('T')[0];-->
<!--                    if (!dateMap[date]) {-->
<!--                        dateMap[date] = 0;-->
<!--                    }-->
<!--                    dateMap[date] += record.totalAmount;-->
<!--                });-->

<!--                // 排序日期-->
<!--                const dates = Object.keys(dateMap).sort();-->
<!--                const amounts = dates.map(date => dateMap[date]);-->

<!--                this.updateChart({ dates, amounts });-->
<!--            },-->

<!--            useMockChartData() {-->
<!--                // 生成模拟图表数据-->
<!--                const dates = [];-->
<!--                const amounts = [];-->
<!--                const today = new Date();-->

<!--                for (let i = 29; i >= 0; i&#45;&#45;) {-->
<!--                    const date = new Date();-->
<!--                    date.setDate(today.getDate() - i);-->
<!--                    dates.push(date.toISOString().split('T')[0]);-->
<!--                    amounts.push(Math.round(Math.random() * 1000 + 500)); // 随机生成500-1500之间的销售额-->
<!--                }-->

<!--                this.updateChart({ dates, amounts });-->
<!--            },-->

<!--            updateChart(chartData) {-->
<!--                const option = {-->
<!--                    tooltip: {-->
<!--                        trigger: 'axis',-->
<!--                        axisPointer: {-->
<!--                            type: 'shadow'-->
<!--                        }-->
<!--                    },-->
<!--                    grid: {-->
<!--                        left: '3%',-->
<!--                        right: '4%',-->
<!--                        bottom: '3%',-->
<!--                        containLabel: true-->
<!--                    },-->
<!--                    xAxis: {-->
<!--                        type: 'category',-->
<!--                        data: chartData.dates,-->
<!--                        axisTick: {-->
<!--                            alignWithLabel: true-->
<!--                        }-->
<!--                    },-->
<!--                    yAxis: {-->
<!--                        type: 'value',-->
<!--                        name: '销售额(元)'-->
<!--                    },-->
<!--                    series: [{-->
<!--                        name: '日销售额',-->
<!--                        type: 'bar',-->
<!--                        barWidth: '60%',-->
<!--                        data: chartData.amounts,-->
<!--                        itemStyle: {-->
<!--                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [-->
<!--                                {offset: 0, color: '#83bff6'},-->
<!--                                {offset: 0.5, color: '#188df0'},-->
<!--                                {offset: 1, color: '#188df0'}-->
<!--                            ])-->
<!--                        }-->
<!--                    }]-->
<!--                };-->

<!--                this.salesChart.setOption(option);-->
<!--            },-->

<!--            formatDateTime(dateTime) {-->
<!--                if (!dateTime) return '';-->
<!--                const date = new Date(dateTime);-->
<!--                return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;-->
<!--            },-->

<!--            navigateTo(url) {-->
<!--                window.location.href = url;-->
<!--            },-->

<!--            handleUserCommand(command) {-->
<!--                if (command === 'profile') {-->
<!--                    window.location.href = 'profile.html';-->
<!--                } else if (command === 'logout') {-->
<!--                    this.handleLogout();-->
<!--                }-->
<!--            },-->

<!--            handleLogout() {-->
<!--                axios.post('/pms/user/logout').then(response => {-->
<!--                    if (response.data.success) {-->
<!--                        this.$message.success('退出登录成功');-->
<!--                        localStorage.removeItem('currentUser');-->
<!--                        window.location.href = 'login.html';-->
<!--                    }-->
<!--                }).catch(error => {-->
<!--                    console.error('退出登录失败:', error);-->
<!--                    localStorage.removeItem('currentUser');-->
<!--                    window.location.href = 'login.html';-->
<!--                });-->
<!--            },-->

<!--            formatRole(role) {-->
<!--                const roleMap = { 'admin': '管理员', 'sales': '销售员', 'inventory': '库存管理员' };-->
<!--                return roleMap[role] || role;-->
<!--            }-->
<!--        }-->
<!--    });-->
<!--</script>-->
<!--</body>-->
<!--</html>-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>药品管理系统 - 销售管理</title>
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.2/dist/echarts.min.js"></script>
    <style>
        /* 样式保持不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
            background-color: #f5f7fa;
            color: #606266;
        }
        .app-container {
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .logo-area {
            display: flex;
            align-items: center;
        }
        .logo {
            width: 50px;
            height: 50px;
            margin-right: 15px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
        }
        .system-name {
            font-size: 22px;
            font-weight: bold;
        }
        .nav-menu {
            display: flex;
            background-color: #304156;
            padding: 0 20px;
        }
        .nav-item {
            padding: 15px 20px;
            color: #bfcbd9;
            cursor: pointer;
            transition: all 0.3s;
        }
        .nav-item:hover, .nav-item.active {
            color: #409EFF;
            background-color: #263445;
            border-bottom: 2px solid #409EFF;
        }
        .main-content {
            flex: 1;
            padding: 20px;
        }
        .card-container {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .search-bar {
            margin-bottom: 20px;
            padding: 20px;
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            text-align: center;
        }
        .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #409EFF;
            margin: 10px 0;
        }
        .stat-label {
            color: #909399;
            font-size: 14px;
        }
        .chart-container {
            height: 300px;
            margin-top: 20px;
        }
        .footer {
            text-align: center;
            padding: 15px 0;
            color: #909399;
            font-size: 14px;
            background-color: #f5f7fa;
            border-top: 1px solid #e6e6e6;
        }
        .positive-amount {
            color: #67C23A;
        }
        .action-buttons {
            margin-bottom: 15px;
        }
        .readonly-input .el-input__inner {
            background-color: #f5f7fa;
            color: #606266;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
<div id="app" class="app-container">
    <header class="header">
        <div class="logo-area">
            <div class="logo">药</div>
            <div class="system-name">药品管理系统</div>
        </div>
        <div>
            <el-dropdown @command="handleUserCommand">
                <span class="el-dropdown-link" style="color: white; cursor: pointer;">
                    {{ currentUser.username }} ({{ formatRole(currentUser.role) }})<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                    <el-dropdown-item command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
    </header>

    <nav class="nav-menu">
        <div class="nav-item" @click="navigateTo('index.html')">首页</div>
        <div class="nav-item" @click="navigateTo('medicine.html')">药品管理</div>
        <div class="nav-item" @click="navigateTo('inventory.html')">库存管理</div>
        <div class="nav-item active">销售管理</div>
        <div class="nav-item" @click="navigateTo('user.html')" v-if="currentUser.role === 'admin'">用户管理</div>
        <div class="nav-item" @click="navigateTo('log.html')" v-if="currentUser.role === 'admin'">操作日志</div>
    </nav>

    <main class="main-content">
        <h2 style="margin-bottom: 20px;">销售管理</h2>

        <div class="stats-container">
            <div class="stat-card">
                <div class="stat-label">今日销售额</div>
                <div class="stat-value">¥{{ salesStats.todaySales || 0 }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">本月销售额</div>
                <div class="stat-value">¥{{ salesStats.monthSales || 0 }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">今日销售单数</div>
                <div class="stat-value">{{ salesStats.todayOrders || 0 }}</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">热销药品</div>
                <div class="stat-value">{{ salesStats.topMedicine || '无' }}</div>
            </div>
        </div>

        <div class="search-bar">
            <el-form :inline="true" :model="searchForm">
                <el-form-item label="药品名称">
                    <el-input v-model="searchForm.medicineName" placeholder="请输入药品名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="销售日期">
                    <el-date-picker
                            v-model="searchForm.dateRange"
                            type="daterange"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                            value-format="yyyy-MM-dd">
                    </el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="loadSales">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button type="success" @click="handleAddSale" v-if="currentUser.role === 'sales' || currentUser.role === 'admin'">新增销售</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="card-container">
            <div class="action-buttons">
                <el-button type="primary" size="small" @click="exportSales">导出数据</el-button>
            </div>

            <el-table :data="salesList" border stripe v-loading="loading">
                <el-table-column prop="id" label="销售ID" width="100"></el-table-column>
                <el-table-column label="药品名称" min-width="150">
                    <template slot-scope="scope">
                        {{ scope.row.medicine ? scope.row.medicine.name : '未知药品' }}
                    </template>
                </el-table-column>
                <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
                <el-table-column label="单价" width="100">
                    <template slot-scope="scope">
                        ¥{{ (scope.row.totalAmount / scope.row.quantity).toFixed(2) }}
                    </template>
                </el-table-column>
                <el-table-column prop="totalAmount" label="总金额" width="120">
                    <template slot-scope="scope">
                        <span class="positive-amount">¥{{ scope.row.totalAmount }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="saleTime" label="销售时间" width="160">
                    <template slot-scope="scope">
                        {{ formatDateTime(scope.row.saleTime) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作员" width="100">
                    <template slot-scope="scope">
                        {{ scope.row.operator ? scope.row.operator.username : '未知' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right" v-if="currentUser.role === 'admin'">
                    <template slot-scope="scope">
                        <el-button size="mini" type="danger" @click="handleDeleteSale(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 由于后端不支持分页，暂时隐藏分页控件 -->
            <!-- <div class="pagination-container">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="pagination.currentPage"
                        :page-sizes="[10, 20, 50, 100]"
                        :page-size="pagination.pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="pagination.total">
                </el-pagination>
            </div> -->
        </div>

        <div class="card-container">
            <h3>销售趋势图</h3>
            <div class="chart-container" id="salesChart"></div>
        </div>

        <!-- 添加销售记录对话框 -->
        <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogVisible"
                width="600px"
                :close-on-click-modal="false">
            <el-form :model="saleForm" :rules="rules" ref="saleForm" label-width="100px">
                <el-form-item label="药品" prop="medicineId">
                    <el-select
                            v-model="saleForm.medicineId"
                            placeholder="请选择药品"
                            filterable
                            @change="onMedicineChange"
                            style="width: 100%;">
                        <el-option
                                v-for="item in availableMedicines"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id">
                            <span style="float: left">{{ item.name }}</span>
                            <span style="float: right; color: #8492a6; font-size: 13px">库存: {{ item.currentStock }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单价">
                    <el-input
                            v-model="saleForm.salePrice"
                            :readonly="true"
                            class="readonly-input"
                            style="width: 100%;">
                        <template slot="prepend">¥</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="数量" prop="quantity">
                    <el-input-number
                            v-model="saleForm.quantity"
                            :min="1"
                            :max="maxQuantity"
                            @change="calculateTotal"
                            style="width: 100%;"></el-input-number>
                    <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                        可用库存: {{ currentStock }}
                    </div>
                </el-form-item>
                <el-form-item label="总金额">
                    <el-input v-model="saleForm.totalAmount" readonly style="width: 100%;">
                        <template slot="prepend">¥</template>
                    </el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitSaleForm">确 定</el-button>
            </span>
        </el-dialog>
    </main>

    <footer class="footer">© 2023 药品管理系统 - 版权所有</footer>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                activeNav: 'sale',
                currentUser: { id: null, username: '', role: '' },
                searchForm: {
                    medicineName: '',
                    dateRange: []
                },
                salesList: [],
                salesStats: {},
                medicines: [],
                availableMedicines: [], // 有库存的药品
                loading: false,
                pagination: {
                    currentPage: 1,
                    pageSize: 10,
                    total: 0
                },
                dialogVisible: false,
                dialogTitle: '新增销售记录',
                saleForm: {
                    medicineId: '',
                    salePrice: 0,
                    quantity: 1,
                    totalAmount: 0
                },
                currentStock: 0,
                maxQuantity: 1,
                rules: {
                    medicineId: [{ required: true, message: '请选择药品', trigger: 'change' }],
                    quantity: [
                        { required: true, message: '请输入销售数量', trigger: 'blur' },
                        { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
                    ]
                },
                salesChart: null
            };
        },
        mounted() {
            this.loadCurrentUser();
            this.loadSales();
            this.loadSalesStats();
            this.loadMedicines();
            this.initChart();

            // 窗口大小变化时重绘图表
            window.addEventListener('resize', () => {
                if (this.salesChart) {
                    this.salesChart.resize();
                }
            });
        },
        methods: {
            loadCurrentUser() {
                // 尝试从本地存储获取用户信息
                const savedUser = localStorage.getItem('currentUser');
                if (savedUser) {
                    this.currentUser = JSON.parse(savedUser);
                    return;
                }

                // 如果本地存储没有，尝试从session获取
                axios.get('/pms/user/current').then(response => {
                    if (response.data.success) {
                        this.currentUser = response.data.data;
                        localStorage.setItem('currentUser', JSON.stringify(response.data.data));
                    } else {
                        this.$message.error('获取用户信息失败');
                        window.location.href = 'login.html';
                    }
                }).catch(error => {
                    console.error('获取用户信息失败:', error);
                    window.location.href = 'login.html';
                });
            },

            loadSales() {
                this.loading = true;

                // 由于后端不支持分页和搜索，我们获取所有数据在前端进行过滤
                axios.get('/pms/sale/list').then(response => {
                    if (response.data.success) {
                        let salesData = response.data.data;

                        // 前端过滤：按药品名称
                        if (this.searchForm.medicineName) {
                            salesData = salesData.filter(sale =>
                                sale.medicine && sale.medicine.name.includes(this.searchForm.medicineName)
                            );
                        }

                        // 前端过滤：按日期范围
                        if (this.searchForm.dateRange && this.searchForm.dateRange.length === 2) {
                            const startDate = new Date(this.searchForm.dateRange[0]);
                            const endDate = new Date(this.searchForm.dateRange[1]);
                            endDate.setHours(23, 59, 59, 999); // 设置为当天结束时间

                            salesData = salesData.filter(sale => {
                                const saleDate = new Date(sale.saleTime);
                                return saleDate >= startDate && saleDate <= endDate;
                            });
                        }

                        this.salesList = salesData;
                        this.pagination.total = salesData.length;
                    } else {
                        if (response.status === 401) {
                            this.$message.error('用户未登录或会话已过期');
                            this.handleLogout();
                        } else {
                            this.$message.error(response.data.message || '获取销售记录失败');
                        }
                    }
                    this.loading = false;
                }).catch(error => {
                    console.error('获取销售记录失败:', error);
                    if (error.response && error.response.status === 401) {
                        this.$message.error('用户未登录或会话已过期');
                        this.handleLogout();
                    } else {
                        this.$message.error('获取销售记录失败');
                    }
                    this.loading = false;
                });
            },

            loadSalesStats() {
                // 计算今天和本月的开始结束日期
                const today = new Date();
                const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

                // 设置时间为一天的开始和结束
                const todayStart = new Date(today);
                todayStart.setHours(0, 0, 0, 0);
                const todayEnd = new Date(today);
                todayEnd.setHours(23, 59, 59, 999);

                const monthStart = new Date(firstDayOfMonth);
                monthStart.setHours(0, 0, 0, 0);
                const monthEnd = new Date(today);
                monthEnd.setHours(23, 59, 59, 999);

                // 获取今天的销售数据
                axios.get('/pms/sale/records/date-range', {
                    params: {
                        startDate: todayStart.toISOString().split('T')[0],
                        endDate: todayEnd.toISOString().split('T')[0]
                    }
                }).then(response => {
                    if (response.data.success) {
                        const todayData = response.data.data;
                        const todaySales = todayData.reduce((sum, record) => sum + record.totalAmount, 0);
                        const todayOrders = todayData.length;

                        // 获取本月的销售数据
                        axios.get('/pms/sale/records/date-range', {
                            params: {
                                startDate: monthStart.toISOString().split('T')[0],
                                endDate: monthEnd.toISOString().split('T')[0]
                            }
                        }).then(response => {
                            if (response.data.success) {
                                const monthData = response.data.data;
                                const monthSales = monthData.reduce((sum, record) => sum + record.totalAmount, 0);

                                // 找出热销药品
                                const medicineSales = {};
                                monthData.forEach(record => {
                                    if (record.medicine && record.medicine.name) {
                                        if (!medicineSales[record.medicine.name]) {
                                            medicineSales[record.medicine.name] = 0;
                                        }
                                        medicineSales[record.medicine.name] += record.quantity;
                                    }
                                });

                                let topMedicine = '无';
                                let maxSales = 0;
                                for (const medicine in medicineSales) {
                                    if (medicineSales[medicine] > maxSales) {
                                        maxSales = medicineSales[medicine];
                                        topMedicine = medicine;
                                    }
                                }

                                this.salesStats = {
                                    todaySales: todaySales.toFixed(2),
                                    monthSales: monthSales.toFixed(2),
                                    todayOrders: todayOrders,
                                    topMedicine: topMedicine
                                };
                            }
                        }).catch(error => {
                            console.error('获取本月销售统计失败:', error);
                        });
                    }
                }).catch(error => {
                    console.error('获取今日销售统计失败:', error);
                });
            },

            loadMedicines() {
                axios.get('/pms/medicine/list').then(response => {
                    if (response.data.success) {
                        this.medicines = response.data.data.content || response.data.data;

                        // 过滤有库存的药品
                        this.availableMedicines = this.medicines.filter(medicine =>
                            medicine.currentStock > 0 && medicine.status === 1
                        );
                    }
                }).catch(error => {
                    console.error('获取药品列表失败:', error);
                });
            },

            resetSearch() {
                this.searchForm = {
                    medicineName: '',
                    dateRange: []
                };
                this.loadSales();
            },

            handleSizeChange(size) {
                this.pagination.pageSize = size;
                this.pagination.currentPage = 1;
                this.loadSales();
            },

            handleCurrentChange(page) {
                this.pagination.currentPage = page;
                this.loadSales();
            },

            handleAddSale() {
                // 检查权限
                if (this.currentUser.role !== 'sales' && this.currentUser.role !== 'admin') {
                    this.$message.error('您没有销售权限');
                    return;
                }

                this.dialogTitle = '新增销售记录';
                this.saleForm = {
                    medicineId: '',
                    salePrice: 0,
                    quantity: 1,
                    totalAmount: 0
                };
                this.currentStock = 0;
                this.maxQuantity = 1;
                this.dialogVisible = true;

                if (this.$refs.saleForm) {
                    this.$refs.saleForm.clearValidate();
                }
            },

            onMedicineChange(medicineId) {
                const medicine = this.medicines.find(m => m.id === medicineId);
                if (medicine) {
                    this.saleForm.salePrice = medicine.price;
                    this.currentStock = medicine.currentStock;
                    this.maxQuantity = medicine.currentStock;
                    this.calculateTotal();
                }
            },

            calculateTotal() {
                this.saleForm.totalAmount = (this.saleForm.quantity * this.saleForm.salePrice).toFixed(2);
            },

            submitSaleForm() {
                this.$refs.saleForm.validate(valid => {
                    if (valid) {
                        // 准备提交数据
                        const saleData = {
                            medicineId: this.saleForm.medicineId,
                            quantity: this.saleForm.quantity,
                            totalAmount: parseFloat(this.saleForm.totalAmount)
                        };

                        axios.post('/pms/sale/add', saleData).then(response => {
                            if (response.data.success) {
                                this.$message.success('销售记录添加成功');
                                this.dialogVisible = false;
                                this.loadSales();
                                this.loadSalesStats();
                                this.loadMedicines(); // 重新加载药品列表以更新库存
                                this.loadChartData();
                            } else {
                                this.$message.error(response.data.message || '添加销售记录失败');
                            }
                        }).catch(error => {
                            console.error('添加销售记录失败:', error);
                            if (error.response && error.response.status === 403) {
                                this.$message.error('权限不足，无法添加销售记录');
                            } else if (error.response && error.response.status === 400) {
                                this.$message.error('库存不足或数据验证失败');
                            } else {
                                this.$message.error('添加销售记录失败');
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },

            handleDeleteSale(row) {
                this.$confirm('确定要删除该销售记录吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 由于后端没有提供删除接口，这里显示提示
                    this.$message.warning('删除功能需要后端支持，请联系管理员');
                }).catch(() => {});
            },

            exportSales() {
                // 由于后端没有提供导出接口，这里使用前端导出
                let csvContent = "data:text/csv;charset=utf-8,"
                    + "销售ID,药品名称,数量,单价,总金额,销售时间,操作员\n";

                this.salesList.forEach(sale => {
                    const row = [
                        sale.id,
                        sale.medicine ? sale.medicine.name : '未知药品',
                        sale.quantity,
                        (sale.totalAmount / sale.quantity).toFixed(2),
                        sale.totalAmount,
                        this.formatDateTime(sale.saleTime),
                        sale.operator ? sale.operator.username : '未知'
                    ].join(',');
                    csvContent += row + "\n";
                });

                const encodedUri = encodeURI(csvContent);
                const link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", "销售记录.csv");
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            },

            initChart() {
                this.salesChart = echarts.init(document.getElementById('salesChart'));
                this.loadChartData();
            },

            loadChartData() {
                // 获取最近30天的销售数据
                const endDate = new Date();
                const startDate = new Date();
                startDate.setDate(startDate.getDate() - 30);

                axios.get('/pms/sale/records/date-range', {
                    params: {
                        startDate: startDate.toISOString().split('T')[0],
                        endDate: endDate.toISOString().split('T')[0]
                    }
                }).then(response => {
                    if (response.data.success) {
                        this.processChartData(response.data.data);
                    }
                }).catch(error => {
                    console.error('获取图表数据失败:', error);
                    // 使用模拟数据作为备选
                    this.useMockChartData();
                });
            },

            processChartData(salesData) {
                // 按日期分组汇总销售数据
                const dateMap = {};

                salesData.forEach(record => {
                    const date = record.saleTime.split('T')[0];
                    if (!dateMap[date]) {
                        dateMap[date] = 0;
                    }
                    dateMap[date] += record.totalAmount;
                });

                // 排序日期
                const dates = Object.keys(dateMap).sort();
                const amounts = dates.map(date => dateMap[date]);

                this.updateChart({ dates, amounts });
            },

            useMockChartData() {
                // 生成模拟图表数据
                const dates = [];
                const amounts = [];
                const today = new Date();

                for (let i = 29; i >= 0; i--) {
                    const date = new Date();
                    date.setDate(today.getDate() - i);
                    dates.push(date.toISOString().split('T')[0]);
                    amounts.push(Math.round(Math.random() * 1000 + 500)); // 随机生成500-1500之间的销售额
                }

                this.updateChart({ dates, amounts });
            },

            updateChart(chartData) {
                const option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '3%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: chartData.dates,
                        axisTick: {
                            alignWithLabel: true
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '销售额(元)'
                    },
                    series: [{
                        name: '日销售额',
                        type: 'bar',
                        barWidth: '60%',
                        data: chartData.amounts,
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {offset: 0, color: '#83bff6'},
                                {offset: 0.5, color: '#188df0'},
                                {offset: 1, color: '#188df0'}
                            ])
                        }
                    }]
                };

                this.salesChart.setOption(option);
            },

            formatDateTime(dateTime) {
                if (!dateTime) return '';
                const date = new Date(dateTime);
                return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
            },

            navigateTo(url) {
                window.location.href = url;
            },

            handleUserCommand(command) {
                if (command === 'profile') {
                    window.location.href = 'profile.html';
                } else if (command === 'logout') {
                    this.handleLogout();
                }
            },

            handleLogout() {
                axios.post('/pms/user/logout').then(response => {
                    if (response.data.success) {
                        this.$message.success('退出登录成功');
                        localStorage.removeItem('currentUser');
                        window.location.href = 'login.html';
                    }
                }).catch(error => {
                    console.error('退出登录失败:', error);
                    localStorage.removeItem('currentUser');
                    window.location.href = 'login.html';
                });
            },

            formatRole(role) {
                const roleMap = { 'admin': '管理员', 'sales': '销售员', 'inventory': '库存管理员' };
                return roleMap[role] || role;
            }
        }
    });
</script>
</body>
</html>